package com.org.matomo.demo;

import ohos.event.commonevent.CommonEventManager;
import ohos.event.commonevent.CommonEventSubscribeInfo;
import ohos.event.commonevent.MatchingSkills;
import ohos.global.resource.NotExistException;
import ohos.global.resource.Resource;
import ohos.global.resource.WrongTypeException;
import ohos.hiviewdfx.HiChecker;
import ohos.hiviewdfx.HiLog;
import ohos.rpc.RemoteException;
import org.matomo.sdk.PackageManagerImpl;
import org.matomo.sdk.TrackerBuilder;
import org.matomo.sdk.extra.*;

import java.io.IOException;
import java.util.EnumSet;

import static org.matomo.sdk.Logger.LABEL;

public class MyApplication extends MatomoApplication {
    private InstallReferrerReceiver subscriber;

    @Override
    public void onEnd() {
        super.onEnd();
        if (subscriber != null) {
            try {
                CommonEventManager.unsubscribeCommonEvent(subscriber);
            } catch (RemoteException e) {
                HiLog.error(LABEL, "Exception occurred during unsubscribeCommonEvent invocation.");
            }
        }
    }

    @Override
    public void onInitialize() {
        super.onInitialize();
        initSubscribeInfo();
        onInitTracker();
        PackageManagerImpl packageManager = new PackageManagerImpl();
        packageManager.setInstallerPackageName(PackageManagerImpl.TARGET_PACKAGE, "");
        EnumSet rules = EnumSet.of(HiChecker.Rule.CAUTION_BY_CRASH, HiChecker.Rule.CAUTION_BY_LOG, HiChecker.Rule.CHECK_VM_RELEASE_MISS);
        HiChecker.addRule(rules);
    }

    @Override
    public TrackerBuilder onCreateTrackerConfig() {
        String baseUrl = null;
        try {
            baseUrl = getResourceManager().getElement(ResourceTable.String_base_url).getString();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (NotExistException e) {
            e.printStackTrace();
        } catch (WrongTypeException e) {
            e.printStackTrace();
        }
        return TrackerBuilder.createDefault(baseUrl, 53);
    }

    private void onInitTracker() {
        // Print debug output when working on an app.

        // When working on an app we don't want to skew tracking results.
        // getMatomo().setDryRun(BuildConfig.DEBUG);

        // If you want to set a specific userID other than the random UUID token, do it NOW to ensure all future actions use that token.
        // Changing it later will track new events as belonging to a different user.
        // String userEmail = ....preferences....getString
        // getTracker().setUserId(userEmail);

        // Track this app install, this will only trigger once per app version.
        // i.e. "http://org.matomo.demo:1/185DECB5CFE28FDB2F45887022D668B4"
        TrackHelper.track().download().identifier(new DownloadTracker.Extra.ApkChecksum(this)).with(getTracker());
        // Alternative:
        // i.e. "http://org.matomo.demo:1/com.android.vending"
        // getTracker().download();

        DimensionQueue mDimensionQueue = new DimensionQueue(getTracker());

        // This will be send the next time something is tracked.
        mDimensionQueue.add(0, "test");
        TrackHelper.track().screens(this).with(this.getTracker());
        getTracker().addTrackingCallback(trackMe -> {
            return trackMe;
        });
    }

    private void initSubscribeInfo() {
        String event = getBundleName();
        MatchingSkills matchingSkills = new MatchingSkills();
        matchingSkills.addEvent(event); // 自定义事件
        CommonEventSubscribeInfo subscribeInfo = new CommonEventSubscribeInfo(matchingSkills);
        subscribeInfo.setPriority(100); // 设置优先级，优先级取值范围[-1000，1000]，值默认为0。
        subscriber = new InstallReferrerReceiver(subscribeInfo, this);
        try {
            CommonEventManager.subscribeCommonEvent(subscriber);
        } catch (RemoteException e) {
            HiLog.error(LABEL, "Exception occurred during subscribeCommonEvent invocation.");
        }
    }
}
